from django.urls import path, reverse

from gideon.service.starlabs import GideonHandler


class ScoreRecordHandler(GideonHandler):
    display_list = ["content", "score", "user", ]
    display_operation_button = []

    def get_queryset(self, handle_type='list', *args, **kwargs):
        student_key = kwargs.get("student_key")
        return self.model_class.objects.filter(student_id=student_key)

    def get_urls(self):
        patterns = [
            # 可以使用面板或者时间树的形式进行展示
            path(r'list/<slug:student_key>/', self.handler_view_list, name=self.get_url_name_list()),
            path(r'add/<slug:student_key>/', self.handler_view_add, name=self.get_url_name_add()),
        ]
        patterns.extend(self.get_extra_urls())
        return patterns

    def reverse_url_add(self, request, *args, **kwargs):
        return self.reverse_handle_url(request, self.get_url_name_add(), student_key=kwargs.get("student_key"))

    def reverse_url_list(self, request, *args, **kwargs):
        name = f'{self.site.namespace}:{self.get_url_name_list()}'
        list_url = reverse(name, kwargs={"student_key": kwargs.get("student_key")})
        params = request.GET.get('_filter')
        if params:
            list_url = f'{list_url}?{params}'
        return list_url

    def saving_pre_handler(self, form, is_update=False, *args, **kwargs):
        current_user_id = self.request.session.get("oracle_users_list")
        if current_user_id:
            current_user_id = current_user_id[0]["key"]
            form.instance.user_id = current_user_id
            form.instance.student_id = kwargs.get("student_key")
            return True
        else:
            return False

    def saving_post_handler(self, form, is_update=False, *args, **kwargs):
        form.instance.student.score += form.instance.score
        form.instance.student.save()
        return True
